function example1s % Solves the BVP and then uses spline interpolation % y'' + p(x)y' + q(x)y= f(x) for xL < x < xr ' % where % y(xl) = yL and y(xR) = yR % p=0, q=-1, f=sin(2*pi*x) % xL=0, yL=0 and xR=1, yR=0 % clear all previous variables and plots clear * clf % set boundary conditions xL=0; yL=0; xR=1; yR=0; % calculate and plot exact solution xx=linspace(xL,xR,100); exact=-sin(2*pi*xx)/(1+4*pi*pi); plot(xx,exact,'k') hold on % define title and axes used in plot xlabel('x-axis','FontSize',14,'FontWeight','bold') ylabel('Solution','FontSize',14,'FontWeight','bold') title('BVP: Example 1 (with splines)','FontSize',14,'FontWeight','bold') % have MATLAB use certain plot options (all are optional) box on % Set the fontsize to 14 for the plot set(gca,'FontSize',14); % loop used to increase N value for in=1:3 % set number of points along the x-axis if in==1 n=2 elseif in==2 n=4 elseif in==3 n=8 end % generate the points along the x-axis, x(1)=xL and x(n+2)=xR x=linspace(xL,xR,n+2); h=x(2)-x(1); % calculate the coefficients of finite difference equation a=zeros(1,n); b=zeros(1,n); c=zeros(1,n); z=zeros(1,n); for i=1:n a(i)=-2+h*h*q(x(i+1)); b(i)=1-0.5*h*p(x(i+1)); c(i)=1+0.5*h*p(x(i+1)); z(i)=h*h*f(x(i+1)); end; z(1)=z(1)-yL*b(1); z(n)=z(n)-yR*c(n); % solve the tri-diagonal matrix problem y=tri(a,b,c,z); y=[yL, y, yR]; % use spline interpolation xs=linspace(xL,xR,200); ys=spline(x,y,xs); % plot the solution if in==1 x1=x; y1=y; %plot(x1,y1,'sr','LineWidth',1,'MarkerSize',7) plot(xs,ys,'--r','LineWidth',1) legend(' Exact',' N = 2',2); set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold'); pause elseif in==2 x2=x; y2=y; %plot(x,y,'ob','LineWidth',1) plot(xs,ys,'--b','LineWidth',1) legend(' Exact',' N = 2',' N = 4',2); set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold'); pause elseif in==3 x3=x; y3=y; %plot(x,y,'*m','LineWidth',1) plot(xs,ys,'--m','LineWidth',1) legend(' Exact',' N = 2',' N = 4',' N = 8',2); end % Set legend font to 14/bold set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold'); end plot(x1,y1,'sr','LineWidth',1,'MarkerSize',7) plot(x2,y2,'ob','LineWidth',1,'MarkerSize',7) plot(x3,y3,'*m','LineWidth',1,'MarkerSize',7) hold off function g=q(x) g=-1; function g=p(x) g=0; function g=f(x) g=sin(2*pi*x); % tridiagonal solver function y = tri( a, b, c, f ) N = length(f); v = zeros(1,N); y = v; w = a(1); y(1) = f(1)/w; for i=2:N v(i-1) = c(i-1)/w; w = a(i) - b(i)*v(i-1); y(i) = ( f(i) - b(i)*y(i-1) )/w; end for j=N-1:-1:1 y(j) = y(j) - v(j)*y(j+1); end